<template>
  <div class="goods">
    <div class="menu-wrapper" ref="menu-wrapper">
      <ul>
        <li v-for="item in goods" :key="item.name" :class="{'current': currentIndex === $index}" @click="selectMenu($index, $event)" class="menu-item">
          <span class="text border-1px">
            <span v-if="item.type>0" :class="classMap[item.type]" class="icon"></span>{{item.name}}
          </span>
        </li>
      </ul>
    </div>
    <div class="foods-wrapper" ref="foods-wrapper">
      <ul>
        <li v-for="item in goods" class="foods-list food-list-hook">
          <h1 class="title">{{item.name}}</h1>
          <ul>
            <li v-for="food in item" class="foods-item">
              <div class="icon">
                <img width="57px" height="57px" :src="food.icon"/>
              </div>
              <div class="content">
                <h2 class="name">{{food.name}}</h2>
                <p class="desc">{{food.description}}</p>
                <div class="extra">
                  <span class="count"> 月售{{food.sellCount}}份</span>
                  <span class="rating">好评率{{food.rating}}%</span>
                </div>
                <div class="price">
                  <span class="now">¥{{food.price}}</span>
                  <span class="old" v-show="food.oldPrice">{{food.oldPrice}}</span>
                </div>
                <div class="cartcontrol-wrapper">
                  <v-cartcontrol :food="food"></v-cartcontrol>
                </div>
              </div>
            </li>
          </ul>
        </li>
      </ul>
    </div>
    <!-- 购物车组件位于页面底部，固定定位: 给子组件传参数,v-ref:在父组件中访问子组件 -->
    <v-shopcart v-ref="shopcart" :select-foods="selectFoods" :delivery-price="seller.deliveryPrice" :min-price="seller.minPrice"></v-shopcart>
  </div>
</template>

<script type="text/ecmascript-6">
  import BScroll from 'better-scroll';
  import shopcart from 'components/shopcart/shopcart';
  import cartcontrol from 'components/cartcontrol/cartcontrol';
  const ERR_OK = 0;

  export default {
    props: {
      seller: {
        type: Object
      }
    },
    data () {
      return {
        goods: [],
        listHeight: [],
        // 右侧滚动的高度
        scrollY: 0
      };
    },
    // 通过计算属性使左右两侧位置对应上
    computed: {
      // 左侧应该在的位置
      currentIndex () {
        for (let i = 0; i < this.listHeight.length; i++) {
          let nowHeight = this.listHeight[i];
          let nextHeight = this.listHeight[i + 1];
          // 两个范围的滚动区间或当前是最后一个
          if (!nextHeight || (this.scrollY >= nowHeight && this.scrollY < nextHeight)) {
            return i;
          }
        }
        return 0;
      },
      // 获取选中的商品
      selectFoods () {
        let foods = [];
        this.goods.forEach((good) => {
          good.foods.forEach((food) => {
            if (food.count) {
              foods.push(food);
            }
          });
        });
        return foods;
      }
    },
    created () {
      this.classMap = ['decrease', 'discount', 'special', 'invoice', 'guarantee'];
      this.$htpp.get('/api/goods').then((response) => {
        response = response.body;
        if (response.errno === ERR_OK) {
          this.goods = response.data;
          // Vue 异步执行 DOM 更新, vue观察到数据变化时会开启一个队列缓存数据再通过watcher触发修改dom，可通过nextTick立即更新DOM
          this.$nextTick(() => {
            this._initScroll();
            // 右侧商品滚动时到指定位置时，左侧对应的菜单高亮
            this._calculateHeight();
          });
        }
      });
    },
    method: {
      // 左侧点击事件(默认点击事件是阻止状态,开启后默认事件会触发2次，所以追加参数event)
      selectMenu(index, event) {
        // _constructed: vue自定义的事件属性, 原生事件没有这个属性,所以当原生事件触发时直接return
        if (!event._constructed) {
          return;
        }
        // 通过左侧菜单找到对应的右侧商品的位置
        let foodList = this.$els.foodsWrapper.getElementsByClassName('food-list-hook');
        let el = foodList[index];
        // 滚动到指定位置
        this.foodsScroll.scrollToElement(el, 300);
      },
      // 封装一个初始化better-scroll的方法: 2个参数
      _initScroll () {
        this.menuScroll = new BScroll(this.$refs.menuWrapper, {
          // 开启可点击状态
          click: true
        });
        this.foodsScroll = new BScroll(this.$refs.foodsWrapper, {
          // 右侧商品在滚动时能实时记录滚动的位置
          probeType: 3,
          click: true
        });
        // 监听滚动事件
        this.foodsScroll.on('scroll', (pos) => {
          // 取整数绝对值
          this.scrollY = Math.abs(Math.round(pos.y));
        });
      },
      _calculateHeight () {
        // 右侧正个区块的高度
        let foodList = this.$els.foodsWrapper.getElementsByClassName('food-list-hook');
        let height = 0;
        this.listHeight.push(height);
        // 依次把每个商品区块的高度放在一个数组中
        for (let i = 0; i < foodList.length; i++) {
          let item = foodList[i];
          height += item.clientHeight;
          this.listHeight.push(height);
        }
      },
      _drop (target) {
        // 调用shopcart中的drop方法, this.$refs.shopcart: 子组件
        // 两个动画同时执行会有卡顿现象,将小球下落动画的动作延时执行
        this.$nextTick(() => {
          this.$refs.shopcart.drop(target);
        });
      }
    },
    // 注册要引入的购物车组件
    compnents: {
      'v-shopcart': shopcart,
      'v-cartcontrol': cartcontrol
    },
    event: {
      'cart.add'(target) {
          this._drop(target);
      }
    }
  };
</script>

<style lang="stylus" rel="stylesheet/stylus">
  @import "../../common/stylus/mixin"
  .goods
    display: flex
    width: 100%
    position: absolute
    top: 174px
    bottom: 46px
    overflow: hidden
    /* 左侧固定，右侧自适应 */
    .menu-wrapper
      /* flex属性是flex-grow, flex-shrink 和 flex-basis的简写，默认值为0 1 auto */
      /* flex-grow属性定义项目的放大比例，默认为0，即如果存在剩余空间，也不放大 */
      /* flex-shrink属性定义了项目的缩小比例，默认为1，即如果空间不足，该项目将缩小 */
      /* flex-basis属性定义了在分配多余空间之前，项目占据的主轴空间。默认值为auto，即项目的本来大小 */
      flex: 0 0 80px
      width: 80px
      background: #f3f5f7
      /* 文字可能有多行且垂直居中 */
      .menu-item
        display: table
        width: 56px
        height:  54px
        line-height: 14px
        padding: 0 12px
        &.current
          margin-top: -1px
          background: #fff
          font-weight: 700
          position: relative
          z-index: 10
          .text
            border-none()
        .icon
          display: inline-block
          vertical-align: top
          width: 12px
          height: 12px
          margin-right: 2px
          background-size: 12px 12px
          background-repeat: no-repeat
          &.decrease
            bg-image('./image/decrease_3')
          &.discount
            bg-image('./image/discount_3')
          &.special
            bg-image('./image/special_3')
          &.invoice
            bg-image('./image/invoice_3')
          &.guarantee
            bg-image('./image/guarantee_3')
        .text
          display: table
          width: 56px
          vertical-align: middle
          font-size: 12px
          border-1px(rgba(7,17,27,0.1))
    .goods-wrapper
      /* 等同于：flex-grow: 1; flex-shrink: 1; flex-basis: 0%; 宽度自适应 */
      flex: 1
      .foods-list
        .title
          padding-left: 14px
          height: 26px
          line-height: 26px
          border-left: 2px solid #d9dde1
          font-size: 12px
          color: rgb(147,153,159)
          background: #f3f5f7
        .foods-item
          display: flex
          margin: 18px
          padding-bottom: 18px
          border-1px: rgba(7,17,27,0.1)
          &:last-child
            border-none()
            margin-bottom: 0px
          .icon
            /* flex属性是flex-grow, flex-shrink 和 flex-basis的简写，默认值为0 1 auto */
            /* flex-grow属性定义项目的放大比例，默认为0，即如果存在剩余空间，也不放大 */
            /* flex-shrink属性定义了项目的缩小比例，默认为1，即如果空间不足，该项目将缩小 */
            /* flex-basis属性定义了在分配多余空间之前，项目占据的主轴空间。默认值为auto，即项目的本来大小 */
            flex: 0 0 57px
            margin-right: 10px
          .content
            /* 宽度自适应 */
            flex: 1
            .name
              margin: 2px 0 8px 0px
              height: 14px
              line-height: 14px
              font-size: 14px
              color: rgb(7,17,27)
            .desc, .extra
              line-height: 10px
              color: rgb(147,153,159)
            .desc
              line-height: 12px
              font-size: 10px
              margin-bottom: 8px
            .extra
              /* 父元素字体大小为0：防止inline-block元素换行时有默认的1px空格产生 */
              font-size: 0
              .count
                margin-right: 12px
                font-size 10px
              .rating
                font-size: 10px
            .price
              font-weight: 700
              line-height: 24px
              .now
                margin-right: 18px
                font-size: 14px
                color: rgb(240,20,20)
              .old
                text-decoration: line-through
                font-size: 10px
                color: rgb(147,153,159)
            .cartcontrol-wrapper
              position: absolute
              right: 0px
              bottom: 12px
</style>
